package com.pactera.madp.cp.common.util.file;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.pactera.madp.admin.api.entity.SysFile;
import com.pactera.madp.admin.api.feign.RemoteFileService;
import com.pactera.madp.admin.api.vo.SysFileVo;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.core.util.SpringContextHolder;
import com.pactera.madp.cp.common.config.FileUploadConfig;
import com.pactera.madp.cp.common.constant.Constant;
import com.pactera.madp.cp.common.enums.FileHandlerEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author lx
 * @date 2021/7/15
 * @desc 文件上传工具类
 */
@Slf4j
public class FilesUtil {

    private static BaseFileHandler client;
    private static RemoteFileService remoteFileService;
    private static FileUploadConfig config;
    private static ExecutorService fileLogPool = Executors.newFixedThreadPool(10);


    static {
        config = SpringContextHolder.getBean(FileUploadConfig.class);
        Class cls = FileHandlerEnum.findByType(config.getUploadType()).getCls();
        client = (BaseFileHandler)SpringContextHolder.getBean(cls);
        remoteFileService = SpringContextHolder.getBean(RemoteFileService.class);
    }

    public static SysFileVo uploadFile(MultipartFile file) {
        return uploadFile(file,null);
    }

    public static SysFileVo uploadFile(MultipartFile file, String fileKey) {
        return uploadFile(file, fileKey, false);
    }

    public static SysFileVo uploadFile(MultipartFile file, String fileKey, boolean isCover) {
        return handFileUpload(file, fileKey, isCover);
    }

    public static SysFileVo uploadFile(File file) {
        return uploadFile(file,null);
    }

    public static SysFileVo uploadFile(File file, String fileKey) {
        return uploadFile(file, fileKey,false);
    }

    public static SysFileVo uploadFile(File file, String fileKey, boolean isCover) {
        return handFileUpload(file, fileKey, isCover);
    }

    public static SysFileVo uploadFile(InputStream in, String fileKey) {
        return uploadFile(in, fileKey, false);
    }

    public static SysFileVo uploadFile(InputStream in, String fileKey, boolean isCover) {
        return handFileUpload(in, fileKey, isCover);
    }

    public static SysFileVo uploadFile(InputStream in, String fileKey, boolean isCover, boolean isUpload) {
        return handFileUpload(in, fileKey, isCover, isUpload);
    }

    public static SysFileVo uploadFile(String base64) {
        return uploadFile(base64, null);
    }

    public static SysFileVo uploadFile(String base64, String fileKey) {
        return uploadFile(base64, fileKey, false);
    }

    public static SysFileVo uploadFile(String base64, String fileKey, boolean isCover) {
        return handFileUpload(base64, fileKey, isCover);
    }

    public static SysFileVo uploadFileByURL(String fileUrl, String fileKey) {
        return handFileUpload(fileUrl, fileKey, false);
    }

    public static SysFileVo uploadFileByURL(String fileUrl, String fileKey, boolean isCover) {
        return handFileUpload(fileUrl, fileKey, isCover);
    }

    public static SysFileVo uploadFileByURL(String fileUrl, String fileKey, boolean isCover, boolean isUpload) {
        return handFileUpload(fileUrl, fileKey, isCover, isUpload);
    }

    /**
     * 批量上传文件
     * @param fileUrlMap key:url value:fileKey
     */
    public static void multipleUploadFile(Map<String,String> fileUrlMap) throws Exception{
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (Map.Entry<String, String> fileUrlInfo : fileUrlMap.entrySet()) {
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    handFileUpload(fileUrlInfo.getKey(), fileUrlInfo.getValue(), false);
                }
            });
        }
    }

    /**
     * 多类型文件处理
     * @param t
     * @param fileKey
     * @param isCover
     * @param <T>
     * @return
     */
    private static <T> SysFileVo handFileUpload(T t, String fileKey, boolean isCover) {
        FileProps props = client.handFileUpload(t, fileKey, isCover);

        if(props == null) {
            props = new FileProps();
            props.setSucceed(false);
            props.setOriginal(fileKey);
        }
        //保存文件
        save(props);
        SysFileVo vo = new SysFileVo();
        BeanUtil.copyProperties(props, vo);
        return vo;
    }

    private static <T> SysFileVo handFileUpload(T t, String fileKey, boolean isCover, boolean isUpload) {
        FileProps props = client.handFileUpload(t, fileKey, isCover, isUpload);

        if(props == null) {
            props = new FileProps();
            props.setSucceed(false);
            props.setOriginal(fileKey);
        }
        //保存文件
        save(props);
        SysFileVo vo = new SysFileVo();
        BeanUtil.copyProperties(props, vo);
        return vo;
    }

    /**
     * 保存文件记录
     * @param props
     * @return
     */
    private static void save(FileProps props) {
        fileLogPool.execute(new Runnable() {
            @Async
            public void run() {
                try {
                    if(!props.getSucceed()) {
                        log.error("-----文件上传失败-----" + props.getOriginal());
                        return;
                    }
                    SysFile sysFile = new SysFile();
                    BeanUtil.copyProperties(props, sysFile);

                    R result = remoteFileService.saveFile(sysFile, SecurityConstants.FROM_IN);
                    if(result != null) {
                        return;
                    }
                }catch (Exception e) {
                    log.error("-----文件日志记录异常-----" + props.getOriginal(),e);
                }
                return;
            }
        });
    }

    /**
     * 获取随机文件名
     * @param extName
     * @return
     */
    public static String getRandomFileName(String extName) {
        if(StrUtil.isEmpty(extName)) {
            throw new IllegalArgumentException("扩展名不以为空");
        }

        return IdUtil.simpleUUID() + StrUtil.DOT + extName;
    }

    /**
     * 获取文件URI
     * @param fileKey
     * @return
     */
    public static String getFileURI(String fileKey) {
        if(StrUtil.isEmpty(fileKey)) {
            throw new IllegalArgumentException("文件key不能为空");
        }
        if(config.getAccessPath() == null) {
            throw new IllegalArgumentException("文件访问Path不存在");
        }

        String uri = config.getAccessPath() + fileKey;
        if(!fileKey.startsWith(Constant.SEPARATOR)) {
            //文件名包含路径处理
            uri = config.getAccessPath() + Constant.SEPARATOR + fileKey;
        }
        return uri;
    }

    /**
     * 通过访问URI获取文件
     * @param uri
     * @return
     */
    public static File getFileByURI(String uri) {
        if(StrUtil.isEmpty(uri)) {
            return null;
        }
        String dest = uri.replace(config.getAccessPath(),config.getRealPath());
        return new File(dest);
    }

    public static FileUploadConfig getConfig() {
        return config;
    }
}
